import { asyncRouterMap, constantRouterMap } from '@/router'

/**
 * 过滤路由
 * 通过遍历路由数据，将子路由path与父path拼接成URL后，匹配后端获取的菜单URL
 * 后端菜单URL中包含拼接后的路由URL，就将与后端正确匹配的路由数据重新填充后返回
 * @param routes asyncRouterMap
 * @param roles
 */
function filterAsyncRouter(routes, menus) {
  const res = []
  if (menus.length === 0) {
    return res
  }
  routes.forEach(route => {
    const tmp = { ...route }
    const chils = []
    if (tmp.children) {
      tmp.children.forEach(chil => {
        const path = tmp.path + '/' + chil.path
        if (menus.includes(path)) {
          chils.push(chil)
        }
      })
      tmp.children = chils
    }
    if (chils.length !== 0) {
      res.push(tmp)
    }
  })
  return res
}

const permission = {
  state: {
    routers: constantRouterMap, //  菜单，用于显示菜单
    addRouters: [] //  路由，用于屏蔽路由地址访问，过滤后剩下的path才可以访问
  },
  mutations: {
    SET_ROUTERS: (state, routers) => {
      state.addRouters = routers
      state.routers = constantRouterMap.concat(routers)
    }
  },
  actions: {
    GenerateRoutes({ commit }, data) {
      return new Promise(resolve => {
        const { menus } = data
        const accessedRouters = filterAsyncRouter(asyncRouterMap, menus)
        commit('SET_ROUTERS', accessedRouters)
        resolve()
      })
    }
  }
}

export default permission
